package com.osdp.uc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.osdp.common.constant.CommonConstant;
import com.osdp.common.exception.PlatformException;
import com.osdp.common.util.BeansUtil;
import com.osdp.common.util.ConvertUtil;
import com.osdp.common.util.MessageUtil;
import com.osdp.common.util.PasswordUtil;
import com.osdp.uc.dto.UserDTO;
import com.osdp.uc.entity.UcPosition;
import com.osdp.uc.entity.UcUser;
import com.osdp.uc.entity.UcUserPosition;
import com.osdp.uc.mapper.UcUserMapper;
import com.osdp.uc.service.IUcPositionService;
import com.osdp.uc.service.IUcUserPositionService;
import com.osdp.sc.service.IScRoleUserService;
import com.osdp.uc.service.IUcUserService;
import com.osdp.sc.vo.ScRoleUserVo;
import com.osdp.uc.vo.UcUserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.osdp.uc.util.Fields.UcUserQ;

@Service
public class UcUserServiceImpl extends ServiceImpl<UcUserMapper,UcUser> implements IUcUserService {

    @Autowired
    private UcUserMapper ucUserMapper;

    @Autowired
    private IScRoleUserService ucUserRoleService;

    @Autowired
    private IUcUserPositionService ucUserPositionService;

    @Autowired
    private IUcPositionService positionService;

    @Override
    public IPage<UcUserVo> pageList(UcUserVo user, Page<UcUser> page) {
        return super.page(page, new QueryWrapper<UcUser>()
                .like(StringUtils.isNotBlank(user.getUserName()), UcUserQ.userName, user.getUserName())
                .like(StringUtils.isNotBlank(user.getRealName()), UcUserQ.realName, user.getRealName())
                .eq(user.getGender() != null,UcUserQ.gender,user.getGender())
                .eq(user.getBirthday() != null, UcUserQ.birthday, user.getBirthday())
                .eq(user.getValidation() != null, UcUserQ.validation, user.getValidation())
                .eq(user.getEntryDate() != null, UcUserQ.entryDate,user.getEntryDate())
                .eq(user.getLeaveDate() !=null, UcUserQ.leaveDate,user.getLeaveDate())
                .eq(StringUtils.isNotBlank(user.getPhone()), UcUserQ.phone, user.getPhone())
                .orderByDesc(UcUserQ.createTime))
                .convert(track ->  BeansUtil.copy(track, new UcUserVo()));
    }

    @Override
    public IPage<UcUserVo> pageListByOrgId(UcUserVo userVo, Page<UcUser> page){
        UcUser entity = ConvertUtil.sourceToTarget(userVo,UcUser.class);
        String orgId = userVo.getOrgId();
        if(CommonConstant.TREE_ROOT_VALUE.equals(orgId)){
            orgId = "";
        }
        return this.ucUserMapper.pageListByOrgId(orgId,entity,page)
                .convert(track ->  BeansUtil.copy(track, new UcUserVo()));
    }

    @Override
    @Transactional
    public boolean insertUser(UcUserVo userVo) {
        long isExistUserName = queryIsExistUserName(userVo.getId(),userVo.getUserName());
        if(isExistUserName > 0){
            throw new PlatformException(MessageUtil.getMessage(10136));
        }
        UcUser entity = ConvertUtil.sourceToTarget(userVo,UcUser.class);
        String salt = ConvertUtil.randomGen(8);
        entity.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(entity.getUserName(), entity.getPassWord(), salt);
        entity.setPassWord(passwordEncode);
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            if(entity.getEntryDate()==null) {
                entity.setEntryDate(sf.parse(sf.format(new Date())));
            }
            entity.setLeaveDate(sf.parse("8888-01-01"));
        } catch (ParseException e) {e.printStackTrace();}
        if(userVo.getIsMajor().equals(CommonConstant.FLAG_ONE_1)){
            entity.setPriorityDepartId(userVo.getOrgId());
        }
        entity.setValidation(CommonConstant.FLAG_ONE_1);
        boolean isSuccess = super.save(entity);
        if(isSuccess) {
            //修改与角色的关系
            List<String> roleIds = userVo.getRoles();
            if(!CollectionUtils.isEmpty(roleIds)) {
                this.ucUserRoleService.batachSaveOrUpdateUserRoleByUserId(entity.getId(), roleIds);
            }
            isSuccess = saveUserRelationInfo(userVo,entity);
        }
//        this.ucUserMapper.insertUser(entity);
        return isSuccess;
    }

    private boolean saveUserRelationInfo(UcUserVo userVo, UcUser entity){
        boolean isSuccess = false;
        UcUserPosition ucUserPosition = new UcUserPosition();
        ucUserPosition.setUserId(entity.getId());
        ucUserPosition.setOrgId(userVo.getOrgId());
        ucUserPosition.setStartDate(entity.getEntryDate());//加入部门时间
        ucUserPosition.setIsMajor(userVo.getIsMajor());
        //可支持一个用户多个职称title,目前只实现支持一个
        ucUserPosition.setTitleId(userVo.getTitleIds());
        //可支持一个用户多个岗位
        String positionIds = userVo.getPositionIds();
        List<String> ids = new ArrayList<>();
        if (StringUtils.isNotBlank(positionIds)) {
            ids = Arrays.asList(positionIds.split(","));
        }
        if(ids.size()>1) {
            List<UcUserPosition> upList = new ArrayList<>();
            for (String id : ids) {
                UcUserPosition uup = new UcUserPosition();
                uup.setUserId(entity.getId());
                uup.setOrgId(userVo.getOrgId());
                uup.setStartDate(entity.getEntryDate());//加入部门时间
                uup.setIsMajor(userVo.getIsMajor());
                uup.setTitleId(userVo.getTitleIds());
                uup.setPositionId(id);
                upList.add(uup);
            }
            isSuccess = ucUserPositionService.saveBatch(upList);
        }else {
            ucUserPosition.setPositionId(ids.get(0));
            isSuccess = ucUserPositionService.save(ucUserPosition);
        }
        return isSuccess;
    }

    @Override
    @Transactional
    public boolean updateUser(UcUserVo userVo) {
        long isExistUserName = queryIsExistUserName(userVo.getId(),userVo.getUserName());
        if(isExistUserName > 0){
            throw new PlatformException(MessageUtil.getMessage(10136));
        }
        UcUser user = super.getById(userVo.getId());
        if (user == null) {
            throw new PlatformException(MessageUtil.getMessage(10054));
        }
        //检查密码强度
//        PasswordUtil.checkPasswordRule(user.getPassWord(), user.getUserName());
        userVo.setPassWord(user.getPassWord());
        UcUser entity = ConvertUtil.sourceToTarget(userVo,UcUser.class);
        if(userVo.getIsMajor().equals(CommonConstant.FLAG_ONE_1)){
            entity.setPriorityDepartId(userVo.getOrgId());
        } else {
            entity.setPriorityDepartId(null);
        }
        entity.setUpdateTime(new Date());
        super.updateById(entity);
        return updateUserRelationInfo(userVo,entity);
    }

    private boolean updateUserRelationInfo(UcUserVo userVo, UcUser entity){
        //修改与角色的关系
        List<String> roleIds = userVo.getRoles();
        if(!CollectionUtils.isEmpty(roleIds)) {
            this.ucUserRoleService.batachSaveOrUpdateUserRoleByUserId(entity.getId(), roleIds);
        }
        // 先删除关系
        ucUserPositionService.deleteUserPosition(userVo.getId(),userVo.getOrgId());
        return saveUserRelationInfo(userVo, entity);
    }

    @Override
    public UcUserVo getByUserId(String id,String orgId) {
        UcUser user = super.getById(id);
        UcUserVo userVo = ConvertUtil.sourceToTarget(user,UcUserVo.class);
        List<ScRoleUserVo> userRoleVoList = this.ucUserRoleService.queryUserRoleByUserId(id);
        List<String> roleIds = new ArrayList<>();
        for(ScRoleUserVo vo : userRoleVoList){
            roleIds.add(vo.getRoleId());
        }
        userVo.setRoles(roleIds);
        List<UcUserPosition> userPositions = ucUserPositionService
                .querUserPositionByUserOrgId(userVo.getId(),orgId);
        if(!CollectionUtils.isEmpty(userPositions)) {
            UcUserPosition userPosition = userPositions.get(0);
            String positionIds = userPositions.stream().map(UcUserPosition::getPositionId).collect(Collectors.joining(","));
            if(StringUtils.isNotBlank(positionIds)) {
                List<UcPosition> positions = positionService.queryPositionByIds(Arrays.asList(positionIds.split(",")));
                if(!CollectionUtils.isEmpty(positions)){
//                    userVo.setPositionNames(JSON.toJSONString(positions));
                    String positionNames = positions.stream().map(UcPosition::getPositionName).collect(Collectors.joining(","));
                    userVo.setPositionNames(positionNames);
                }
            }
            userVo.setPositionIds(positionIds);
            userVo.setTitleIds(userPosition.getTitleId());
            userVo.setIsMajor(userPosition.getIsMajor());
        }
        return userVo;
    }

    /**
     * 查询判断用户名是否存复
     * @param id
     * @param userName
     * @return
     */
    @Override
    public long queryIsExistUserName(String id, String userName){
        QueryWrapper query = new QueryWrapper<UcUser>();
        query.eq(StringUtils.isNotBlank(userName), UcUserQ.userName,userName);
        if(StringUtils.isNotBlank(id)){
            query.ne(UcUserQ.id, id); // 不等于<>
        }
        return super.count(query);
    }

    @Override
    @Transactional
    public boolean updatePassWord(String id, String passWord) {
        UcUser entity = super.getById(id);
        if (entity == null) {
            throw new PlatformException(MessageUtil.getMessage(10054));
        }
        String salt = ConvertUtil.randomGen(8);
        String passwordEncode = PasswordUtil.encrypt(entity.getUserName(), passWord, salt);
        return super.update(entity,new UpdateWrapper<UcUser>()
                .set(UcUserQ.passWord,passwordEncode)
                        .set(UcUserQ.salt,salt)
                .eq(UcUserQ.id,id));
    }

    @Override
    @Transactional
    public boolean updateValidation(String[] ids, String  status) {
        boolean isSuccess = false;
        for(String id: ids) {
            UcUser user = super.getById(id);
            if (user == null) {
                throw new PlatformException(MessageUtil.getMessage(10054));
            }
            isSuccess = super.update(user, new UpdateWrapper<UcUser>()
                    .set(UcUserQ.validation, status)
                    .eq(UcUserQ.id, id));
        }
        return isSuccess;
    }

    @Override
    @Transactional
    public boolean deleteUser(String id, String orgId){
        this.ucUserRoleService.deleteByUserId(id);//根据用户ID删除用户与角色的关系
        if(StringUtils.isNotBlank(orgId)) {
            this.ucUserPositionService.deleteUserPosition(id, orgId);
        }
        return super.removeById(id);
    }

    @Override
    @Transactional
    public boolean deleteBatcah(List<String> ids,String orgId){
        for (String id: ids) {
            this.ucUserRoleService.deleteByUserId(id);//根据用户ID删除用户与角色的关系
            if (StringUtils.isNotBlank(orgId)) {
                this.ucUserPositionService.deleteUserPosition(id, orgId);
            }
        }
        return super.removeByIds(ids);
    }

    //-----------------------------用于用户登录---------------------------------//

    @Override
    public UserDTO queryUserByUserName(String userName) {
        UcUser entity = super.getOne(new QueryWrapper<UcUser>()
                .eq(StringUtils.isNotBlank(userName), UcUserQ.userName,userName));
        return ConvertUtil.sourceToTarget(entity, UserDTO.class);
    }

    @Override
    public UserDTO queryUserById(String userId) {
        UcUser entity = super.getById(userId);
        return  ConvertUtil.sourceToTarget(entity, UserDTO.class);
    }

    @Override
    public IPage<UserDTO> userPageList(UserDTO user, Page<UcUser> page) {
        return super.page(page, new QueryWrapper<UcUser>()
                        .like(StringUtils.isNotBlank(user.getUserName()), UcUserQ.userName, user.getUserName())
                        .like(StringUtils.isNotBlank(user.getRealName()), UcUserQ.realName, user.getRealName())
                        .eq(user.getGender() != null,UcUserQ.gender,user.getGender())
                        .eq(user.getBirthday() != null, UcUserQ.birthday, user.getBirthday())
                        .eq(user.getValidation() != null, UcUserQ.validation, user.getValidation())
                        .eq(user.getEntryDate() != null, UcUserQ.entryDate,user.getEntryDate())
                        .eq(user.getLeaveDate() !=null, UcUserQ.leaveDate,user.getLeaveDate())
                        .eq(StringUtils.isNotBlank(user.getPhone()), UcUserQ.phone, user.getPhone())
                        .orderByDesc(UcUserQ.createTime))
                .convert(track ->  BeansUtil.copy(track, new UserDTO()));
    }

}
